import 'dart:convert';
import 'dart:ui';

import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:xin_he/page/goods/xin_he_photo_gallery_scan/xin_he_photo_gallery_scan_view.dart';
import 'package:xin_he/page/shopping_car/xin_he_goods_payment/xin_he_instant_buy/xin_he_instant_buy_view.dart';
import 'package:xin_he/routes/xin_he_routes.dart';
import 'package:xin_he/utils/xh_styles.dart';
import 'package:xin_he/utils/xin_he_image.dart';

import '../../../utils/xin_he_toast.dart';
import 'xin_he_good_detail_logic.dart';

class XinHeGoodDetailPage extends StatelessWidget {
  XinHeGoodDetailPage({Key? key}) : super(key: key);

  final logic = Get.put(XinHeGoodDetailLogic());
  final state = Get.find<XinHeGoodDetailLogic>().state;

  @override
  Widget build(BuildContext context) {
    return Obx(() => Scaffold(
      body: Stack(children: [
        Stack(children: [
          ListView(
            padding: EdgeInsets.zero,
            children: [

              ///图片banner
              Listener(
                onPointerDown: logic.getPointDownListenerInHorizontal(),
                onPointerUp: logic.getPointUpListenerInHorizontal(),
                child: SizedBox(
                  height: 300,
                  width: Get.width,
                  child: ListView.builder(
                      padding: EdgeInsets.zero,
                      itemCount: state.images.length,
                      scrollDirection: Axis.horizontal,
                      controller: logic.scrollController,
                      itemBuilder: (ctx,index){

                        return GestureDetector(
                          onTap: ()async{

                            Map map = {'images':state.images.value,'index':index};
                            String json = jsonEncode(map);
                            Get.toNamed(XinHeRoutes.goodsDetailBannerScan,arguments: logic.test,parameters:{'data':json});

                            // await Navigator.of(context).push(XinHeFadeRoute(page: XinHePhotoGalleryScanPage(imagesList: state.images.value,currentIndex: index,))).then((value) => {})
                                ;
                          },
                          child: Container(
                            color: Colors.white,
                            width: Get.width,
                            height: 300,
                            child:
                              XinHeNetImage(url: state.images.value[index]??'',)
                            // XinHeAssetImage('assets/images/adopt/bg_${index+1}.png',fit: BoxFit.contain,),
                          ),
                        );
                      }
                  ),),
              ),


              Container(
                margin: const EdgeInsets.symmetric(horizontal: 15,vertical: 15),
                padding: const EdgeInsets.symmetric(horizontal: 15,vertical: 0),
                decoration: BoxDecoration(color: Colors.white,borderRadius: BorderRadius.circular(10)),
                child:  Row(
                  mainAxisSize: MainAxisSize.max,
                  mainAxisAlignment: MainAxisAlignment.start,
                  children: [
                    Expanded(
                      child: Padding(
                        padding: const EdgeInsets.only(right: 15),
                        child: Column(
                          crossAxisAlignment: CrossAxisAlignment.start,
                          children: [
                            const SizedBox(height: 10,),
                            Text(logic.model.value.name??'',maxLines: 2,style: TextStyle(color: XinHeColor('#2B3131'),fontSize: 17,fontWeight: FontWeight.w600),softWrap: true,),
                            const SizedBox(height: 10,),
                            RichText(
                                text: TextSpan(children: [
                                  ///￥
                                  TextSpan(
                                    text: '￥',
                                    style: TextStyle(
                                      color: XinHeColor('#E84128'),
                                      fontSize: 9,
                                      fontWeight: FontWeight.w500,
                                    ),
                                  ),

                                  ///
                                  TextSpan(
                                    text: '${logic.model.value.price??0}',
                                    style: TextStyle(
                                      color: XinHeColor('#E84128'),
                                      fontSize: 16,
                                      fontWeight: FontWeight.w500,
                                    ),
                                  ),

                                ]
                                )),
                            const SizedBox(height: 15,)


                          ],),
                      ),
                    ),
                    SizedBox(
                      width: 30,
                      child: Column(
                        children: [
                          const XinHeAssetImage('assets/images/home/favor.png',width: 18,height: 18,),
                          Text('收藏',style: TextStyle(color: XinHeColor('#A8B0B0'),fontSize: 11),)
                        ],
                      ),
                    ),
                    SizedBox(width: 15,),
                    SizedBox(
                      width: 30,
                      child: Column(
                        children: [
                          const XinHeAssetImage('assets/images/home/share.png',width: 18,height: 18,),
                          Text('分享',style: TextStyle(color: XinHeColor('#A8B0B0'),fontSize: 11),)
                        ],
                      ),
                    ),


                  ],),
              ),

              ///规格、发货、保障
              Container(
                margin: const EdgeInsets.symmetric(horizontal: 15,vertical: 0),
                decoration: BoxDecoration(color: Colors.white,borderRadius: BorderRadius.circular(10)),
                child: Padding(
                  padding: const EdgeInsets.all(15.0),
                  child: Column(children: [

                    Row(children: [
                      Text('选择规格',style: TextStyle(color: XinHeColor('#8B9191'),fontSize: 13,fontWeight: FontWeight.w500),),
                      Spacer(),
                      const XinHeAssetImage('assets/images/mine/mine_arrow.png',width: 6,height: 10,)

                    ],),

                    const SizedBox(height: 10,),
                    Row(children: [
                      Text('发货',style: TextStyle(color: XinHeColor('#8B9191'),fontSize: 13,fontWeight: FontWeight.w500),),
                      Spacer(),
                      Text(logic.model.value.sendAddress??'',style: TextStyle(color: XinHeColor('#8B9191'),fontSize: 13,fontWeight: FontWeight.w500),)

                    ],),
                    const SizedBox(height: 10,),

                    Row(children: [
                      Text('保障',style: TextStyle(color: XinHeColor('#8B9191'),fontSize: 13,fontWeight: FontWeight.w500),),
                      Spacer(),
                      Text('48小时退换货',style: TextStyle(color: XinHeColor('#8B9191'),fontSize: 13,fontWeight: FontWeight.w500),)

                    ],),

                  ],),
                ),),


             ListView.builder(
                physics: const NeverScrollableScrollPhysics(),
                shrinkWrap: true,
                padding: EdgeInsets.only(left: 15,right: 15,top: 15,bottom:15+60+Get.mediaQuery.padding.bottom ),
                 itemBuilder: (ctx,index){
               return XinHeNetImage(url: state.bottomImages[index],width: Get.width-30,fit: BoxFit.fitWidth);},
                 itemCount: state.bottomImages.length,
             ),

              // Container(
              //     margin: const EdgeInsets.only(left: 15,right: 15,top: 15),
              //     child: XinHeAssetImage('assets/images/adopt/bg_1.png',width: Get.width-30,fit: BoxFit.fitWidth,)
              // ),
              // Container(
              //     margin: const EdgeInsets.symmetric(horizontal: 15,vertical: 0),
              //     child: XinHeAssetImage('assets/images/adopt/bg_2.png',width: Get.width-30,fit: BoxFit.fitWidth,)
              // ),
              // Container(
              //     margin:  EdgeInsets.only(left: 15,right: 15,bottom: 15+60+Get.mediaQuery.padding.bottom),
              //     child: XinHeAssetImage('assets/images/adopt/bg_3.png',width: Get.width-30,fit: BoxFit.fitWidth,)
              // ),

            ],),
        ],),

        ///顶部bar
        Positioned(
          left: 10,
          top: Get.mediaQuery.padding.top,
          child: Padding(
            padding: const EdgeInsets.symmetric(horizontal: 5),
            child: GestureDetector(
              onTap: (){
                Get.back();
              },
              behavior: HitTestBehavior.opaque,
              child: Container(
                height: 44,
                width: 40,
                color: Colors.transparent,
                alignment: Alignment.centerLeft,
                child: const XinHeAssetImage(
                  'assets/images/home/app_back_3.png',
                  width: 9.5,
                  height: 17,
                  fit: BoxFit.cover,),
              ),
            ),
          ),
        ),

        ///底部bar
        Positioned(
            bottom: 0,
            left: 0,
            right: 0,
            child: Container(
              height: 60+Get.mediaQuery.padding.bottom,
              padding: EdgeInsets.symmetric(horizontal: 15),
              color: Colors.white,
              alignment: Alignment.center,
              child: Column(
                mainAxisAlignment: MainAxisAlignment.start,
                children: [
                  SizedBox(
                    height: 60,
                    child: Row(
                      crossAxisAlignment: CrossAxisAlignment.center,
                      children: [
                        GestureDetector(
                          onTap: (){
                            Get.toNamed(XinHeRoutes.sellerShop);
                          },
                          child: Center(
                            child: Column( mainAxisAlignment: MainAxisAlignment.center,
                              children: [
                                const XinHeAssetImage('assets/images/home/shop_icon.png',width: 26,height: 26,),
                                const SizedBox(height: 2,),
                                Text('店铺',style: TextStyle(color: XinHeColor('#2B3131'),fontSize: 12,fontWeight: FontWeight.w500),)
                              ],),
                          ),
                        ),
                        const SizedBox(width: 25,),
                        GestureDetector(
                          onTap: (){
                            XinHeToast.center('正在开发，敬请期待');

                          },
                          child: Container(
                            color: Colors.transparent,
                            child: Column(mainAxisAlignment: MainAxisAlignment.center,
                              children: [
                                const XinHeAssetImage('assets/images/home/service_icon.png',width: 26,height: 26,),
                                const SizedBox(height: 2,),
                                Text('客服',style: TextStyle(color: XinHeColor('#2B3131'),fontSize: 12,fontWeight: FontWeight.w500),)
                              ],),
                          ),
                        ),
                        const Spacer(),
                        GestureDetector(
                          onTap: (){
                            // logic.addToCart();

                            if(state.specificationList.isNotEmpty){
                              logic.toPage(0);

                            }

                          },
                          child: Container(
                            padding: const EdgeInsets.symmetric(horizontal: 15),
                            alignment: Alignment.center,
                            height: 42,
                            decoration:  BoxDecoration(
                              color: Colors.white,
                              border: Border.all(color: XinHeColor('#FF892F'),width: 0.5),
                              borderRadius: const BorderRadius.only(topLeft: Radius.circular(21),bottomLeft: Radius.circular(21)),
                            ),
                            child: Text('加入购物车',style: TextStyle(color: XinHeColor('#F37D2D'),fontWeight: FontWeight.w600,fontSize: 17),strutStyle: const StrutStyle(forceStrutHeight: true),),

                          ),
                        ),
                        GestureDetector(
                          onTap: (){
                            // Get.toNamed(XinHeRoutes.instantBuy,arguments: logic.model.value);

                            // logic.requestGoodSpecification();
                            if(state.specificationList.isNotEmpty){
                              logic.toPage(1);

                            }
                            // Get.bottomSheet(XinHeInstantBuyPage(dataModel: logic.model.value,),persistent: false,isScrollControlled: true);

                          },
                          child: Container(
                            padding: const EdgeInsets.symmetric(horizontal: 15),
                            alignment: Alignment.center,
                            height: 42,
                            decoration:  BoxDecoration(
                              // color: Colors.white,
                              gradient: LinearGradient(colors: [XinHeColor('#F89A30'),XinHeColor('#E84128')]),
                              border: Border.all(color: XinHeColor('#FF892F'),width: 0.5),
                              borderRadius: const BorderRadius.only(topRight: Radius.circular(21),bottomRight: Radius.circular(21)),
                            ),
                            child: Text('立即购买',style: TextStyle(color: Colors.white,fontWeight: FontWeight.w600,fontSize: 17),strutStyle: StrutStyle(forceStrutHeight: true),),

                          ),
                        ),

                      ],
                    ),
                  ),
                ],),

            ))

      ],),
    ));
  }




//   PointerDownEventListener getPointDownListenerInHorizontal() {
//     return (event) {
//       logic.pointerStart = event.position;
//     };
//   }
//
//   PointerUpEventListener getPointUpListenerInHorizontal() {
//
//     return (event){
//       logic.pointerEnd = event.position;
//       logic.touchRangeX = logic.pointerStart.dx - logic.pointerEnd.dx;
//       logic.touchRangeY =logic.pointerStart.dy - logic.pointerEnd.dy;
//
//       double screenWidth = Get.width;
//       //所有的操作必须要满足滑动距离>10才算是滑动
//       if (logic.touchRangeX.abs() < 10) {
//         logic.nextOffset = screenWidth * logic.lastPage;
//         animateToOffset(logic.scrollController, logic.nextOffset, () {
//           if (logic.lastPage < 0) {
//             logic.lastPage = 0;
//           }
//         });
//         return;
//       }
//       //纵向操作大于横向操作三倍视为纵向操作
//       //这个判断拦截只有在纵向操作距离大于20.0的时候才生效
//       if (logic.touchRangeX.abs() < logic.touchRangeY.abs() && logic.touchRangeY > 20) {
//         logic.nextOffset = screenWidth * logic.lastPage;
//         animateToOffset(logic.scrollController, logic.nextOffset, () {
//           if (logic.lastPage < 0) {
//             logic.lastPage = 0;
//           }
//         });
//         return;
//       }
//
//       //如果滑动小于当前屏幕1/8，那么就回弹复原，超过则移动到下一页
//       //跳转到下一页或者上一页或者不动
//       if (logic.touchRangeX > screenWidth / 8) {
//         logic.nextOffset = screenWidth * (logic.lastPage + 1);
//         print("animate to ${logic.nextOffset}");
//         animateToOffset(logic.scrollController, logic.nextOffset, () {
//           logic.lastPage++;
//           if (logic.lastPage >= state.images.length - 1) {
//             logic.lastPage = state.images.length - 1;
//           }
//         });
//       } else if (logic.touchRangeX < -1 * screenWidth / 8) {
//         logic.nextOffset = screenWidth * (logic.lastPage - 1);
//         print("animate to ${logic.nextOffset}");
//         animateToOffset(logic.scrollController, logic.nextOffset, () {
//           logic.lastPage--;
//           if (logic.lastPage < 0) {
//             logic.lastPage = 0;
//           }
//         });
//       } else {
//         animateToOffset(logic.scrollController, screenWidth * logic.lastPage, (){});
//       }
//     };
//
//   }
//
//   void animateToOffset(ScrollController controller, double offset,
//       void Function() onScrollCompleted) {
//     controller
//         .animateTo(offset,
//         duration: Duration(milliseconds: 200), curve: Curves.easeIn)
//         .then((value) {
//       if (onScrollCompleted != null) {
//         onScrollCompleted();
//       }
//     }).catchError((e) {
//       print(e);
//     });
//   }
}

class XinHeFadeRoute extends PageRouteBuilder {
  final Widget page;
  XinHeFadeRoute({required this.page}):super(
    pageBuilder: (
        BuildContext context,
        Animation<double> animation,
        Animation<double> secondaryAnimation,
        ) => page,transitionsBuilder: (
      BuildContext context,
      Animation<double> animation,
      Animation<double> secondaryAnimation,
      Widget child,
      ) => FadeTransition(opacity: animation,child: child,),
  );
}
